#include "CharacterManager.h"
#include <iostream>
#include <string>

using namespace std;


CharacterManager::CharacterManager(bool deleteUnusedTextures)
{
	DelUnText = deleteUnusedTextures;
}

Character* CharacterManager::newChr(string tex)
{
	itMP itMP_B = MP.begin();
	itMP itMP_E = MP.end();
	bool hit = false;
	Texture* _tex;

	for(itMP it = itMP_B; it !=itMP_E; it++)
	{
		if (it->first == tex) 
		{
			_tex = it->second.first;
			it->second.second++;
			hit = true;
			break;
		}
	}
	
	if(!hit)
	{	
		_tex = new Texture(tex);
		pair<Texture*,int> pr(_tex,1);
		MP[tex] = pr;
		rpt.TextureCreatedCount++;
		rpt.TexCount++;
	}
	
	rpt.ChrCreatedCount++;
	Character *chr = new Character(_tex);
	
	if(rpt.TexCount > rpt.MaxTex)
	{
		rpt.MaxMemoryUsed = sizeof(*_tex) * rpt.TexCount;
		rpt.MaxTex = rpt.TexCount;
	}

	return chr;
}

void CharacterManager::delChr(Character *chr)
{
	if(MP.empty())
	{
		cout << "El character " << chr->getText() << " no percenece a este character manager" << endl;
		return;
	}
		

	itMP itMP_B = MP.begin();
	itMP itMP_E = MP.end();
	bool found = false;

	for(itMP it = itMP_B; it !=itMP_E; it++)
	{
		if (it->first == chr->getText()) 
		{
			found = true;
			if(it->second.second == 1)
			{
				if(DelUnText)
				{
					delete it->second.first;
					it->second.first = NULL;
					MP.erase(it);
					rpt.TextureDeletedCount++;
					rpt.TexCount--;
					break;
				}else
				{
					it->second.second--;
				}
			}else it->second.second--; 
			rpt.ChrDeletedCount++;
		}
	}
	if(!found)cout << "El character " << chr->getText() << " no percenece a este character manager" << endl;
}

Report CharacterManager::getReport()
{
	if(!MP.empty())
	{
		itMP itMP_B = MP.begin();
		itMP itMP_E = MP.end();

		for(itMP it = itMP_B; it !=itMP_E; it++)
		{
			rpt.TextureUndeleted += " " + it->first;
			rpt.MemoryLeaked += sizeof(*it->second.first);
		}
	}
		
	return rpt;
}
